<template>
  <div class="user-example">
    <h2>👤 用户管理示例 - Actions与异步操作</h2>
    
    <div class="user-container">
      <!-- 用户状态显示 -->
      <div class="user-status">
        <div class="status-card">
          <h3>{{ userDisplayName }}</h3>
          <div v-if="user.isLoggedIn" class="user-info">
            <p><strong>邮箱:</strong> {{ user.email }}</p>
            <p><strong>状态:</strong> <span class="status-online">在线</span></p>
          </div>
          <div v-else class="login-prompt">
            <p>请登录以获取完整功能</p>
          </div>
        </div>
      </div>
      
      <!-- 登录表单 -->
      <div v-if="!user.isLoggedIn" class="login-section">
        <h3>🔐 用户登录</h3>
        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="email">邮箱地址:</label>
            <input 
              id="email"
              v-model="loginForm.email"
              type="email"
              placeholder="admin@test.com"
              required
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label for="password">密码:</label>
            <input 
              id="password"
              v-model="loginForm.password"
              type="password"
              placeholder="123456"
              required
              class="form-input"
            >
          </div>
          <button 
            type="submit" 
            :disabled="loading"
            class="btn btn-primary btn-full"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </form>
        
        <!-- 登录提示 -->
        <div class="login-hint">
          <p><strong>测试账号:</strong></p>
          <p>邮箱: admin@test.com</p>
          <p>密码: 123456</p>
        </div>
        
        <!-- 错误信息显示 -->
        <div v-if="loginError" class="error-message">
          {{ loginError }}
        </div>
      </div>
      
      <!-- 已登录用户操作 -->
      <div v-else class="user-actions">
        <h3>⚙️ 用户操作</h3>
        <div class="action-buttons">
          <button @click="handleLogout" class="btn btn-secondary">
            退出登录
          </button>
          <button @click="showProfile = !showProfile" class="btn btn-info">
            {{ showProfile ? '隐藏' : '显示' }}个人资料
          </button>
        </div>
        
        <!-- 个人资料编辑 -->
        <div v-if="showProfile" class="profile-section">
          <h4>个人资料</h4>
          <div class="form-group">
            <label>用户名:</label>
            <input 
              v-model="profileForm.name"
              type="text"
              class="form-input"
            >
          </div>
          <div class="form-group">
            <label>邮箱:</label>
            <input 
              v-model="profileForm.email"
              type="email"
              class="form-input"
            >
          </div>
          <button @click="updateProfile" class="btn btn-success">
            更新资料
          </button>
        </div>
      </div>
      
      <!-- 加载状态指示器 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p>处理中...</p>
      </div>
    </div>
    
    <!-- 学习说明 -->
    <div class="explanation">
      <h3>🚀 这个示例演示了：</h3>
      <div class="concept-grid">
        <div class="concept-item">
          <h4>Actions异步操作</h4>
          <p>模拟登录API请求，展示如何在action中处理异步逻辑</p>
        </div>
        <div class="concept-item">
          <h4>Loading状态管理</h4>
          <p>使用store管理全局loading状态，提供更好的用户体验</p>
        </div>
        <div class="concept-item">
          <h4>错误处理</h4>
          <p>在action中捕获错误，并通过返回值传递给组件</p>
        </div>
        <div class="concept-item">
          <h4>复杂数据更新</h4>
          <p>演示如何更新复杂对象状态（用户信息）</p>
        </div>
      </div>
      
      <div class="code-tips">
        <h4>💡 关键代码模式：</h4>
        <ul>
          <li><code>async/await</code> 在actions中处理异步操作</li>
          <li><code>try/catch</code> 错误处理模式</li>
          <li><code>commit</code> 在action中调用mutation</li>
          <li><code>loading状态</code> 管理用户界面状态</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'UserExample',
  data() {
    return {
      loginForm: {
        email: '',
        password: ''
      },
      profileForm: {
        name: '',
        email: ''
      },
      showProfile: false,
      loginError: ''
    }
  },
  computed: {
    // 映射store状态
    ...mapState(['user', 'loading']),
    ...mapGetters(['userDisplayName'])
  },
  watch: {
    // 监听用户登录状态变化，自动填充表单
    'user.isLoggedIn'(newVal) {
      if (newVal) {
        this.profileForm.name = this.user.name
        this.profileForm.email = this.user.email
        this.loginError = ''
      }
    }
  },
  methods: {
    // 映射store actions
    ...mapActions(['login', 'logout']),
    
    // 处理登录
    async handleLogin() {
      this.loginError = ''
      
      try {
        const result = await this.login({
          email: this.loginForm.email,
          password: this.loginForm.password
        })
        
        if (result.success) {
          // 登录成功，清空表单
          this.loginForm.email = ''
          this.loginForm.password = ''
          
          // 显示成功消息
          this.$nextTick(() => {
            alert(result.message)
          })
        } else {
          // 登录失败，显示错误信息
          this.loginError = result.message
        }
      } catch (error) {
        this.loginError = '登录时发生错误，请稍后重试'
        console.error('Login error:', error)
      }
    },
    
    // 处理退出登录
    handleLogout() {
      if (confirm('确定要退出登录吗？')) {
        this.logout()
        this.showProfile = false
        this.loginError = ''
      }
    },
    
    // 更新个人资料
    updateProfile() {
      // 这里我们直接调用store的SET_USER mutation
      // 在实际应用中，这应该是一个API调用
      this.$store.commit('SET_USER', {
        name: this.profileForm.name,
        email: this.profileForm.email
      })
      
      alert('个人资料更新成功！')
    }
  },
  
  // 组件创建时的处理
  created() {
    // 如果用户已登录，填充表单数据
    if (this.user.isLoggedIn) {
      this.profileForm.name = this.user.name
      this.profileForm.email = this.user.email
    }
  }
}
</script>

<style scoped>
.user-example {
  max-width: 700px;
  margin: 0 auto;
  padding: 20px;
}

.user-container {
  background: #fff;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  position: relative;
}

.user-status {
  margin-bottom: 30px;
}

.status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px;
  border-radius: 12px;
  text-align: center;
}

.status-card h3 {
  margin: 0 0 15px 0;
  font-size: 1.5rem;
}

.user-info p {
  margin: 8px 0;
  opacity: 0.9;
}

.status-online {
  background: #28a745;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.login-prompt {
  opacity: 0.8;
}

.login-section {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.login-section h3 {
  margin-bottom: 20px;
  color: #495057;
}

.login-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #dee2e6;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #007bff;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 10px;
  margin-bottom: 10px;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-full {
  width: 100%;
  margin-right: 0;
}

.login-hint {
  background: #e7f3ff;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #007bff;
  margin-bottom: 15px;
}

.login-hint p {
  margin: 5px 0;
  color: #495057;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  padding: 12px 16px;
  border-radius: 6px;
  border: 1px solid #f5c6cb;
}

.user-actions {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
}

.user-actions h3 {
  margin-bottom: 20px;
  color: #495057;
}

.action-buttons {
  margin-bottom: 20px;
}

.profile-section {
  background: white;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #dee2e6;
}

.profile-section h4 {
  margin-bottom: 15px;
  color: #495057;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 12px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.explanation {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 12px;
  border-left: 5px solid #17a2b8;
}

.explanation h3 {
  color: #2c3e50;
  margin-bottom: 20px;
}

.concept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 25px;
}

.concept-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.concept-item h4 {
  color: #495057;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.concept-item p {
  color: #6c757d;
  font-size: 0.9rem;
  line-height: 1.5;
}

.code-tips {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.code-tips h4 {
  color: #495057;
  margin-bottom: 15px;
}

.code-tips ul {
  list-style: none;
  padding: 0;
}

.code-tips li {
  padding: 8px 0;
  border-bottom: 1px solid #dee2e6;
}

.code-tips li:last-child {
  border-bottom: none;
}

code {
  background: #e9ecef;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  color: #e83e8c;
}
</style>